<template>
  <div class="personnel-manage-list" id="invite-personel-warp">
    <a-card :bordered="false" style="width: 100%">
      <div slot="title">
        <a-icon type="left" class="mr10" @click="goBack" />
        <span> {{ title }} </span>
      </div>
      <span slot="extra">
        <a-button
          v-if="!roleId"
          type="primary"
          class="mr10"
          @click="onAddUser"
          icon="user"
          >邀请人员</a-button
        >
      </span>
      <a-table
        :columns="personnelColumnsPri"
        :data-source="userData"
        :scroll="{ x: 1000 }"
        :rowKey="(record) => record.id"
        :loading="isLoading"
        :pagination="{
          showTotal: () => `总共${pagination.total}条`,
          showQuickJumper: true,
          showSizeChanger: true,
          total: pagination.total,
          current: pagination.currentPage,
          pageSize: pagination.pageSize,
        }"
        @change="onTableChange"
      >
        <template slot="authority" slot-scope="text, record">
          <a-button type="primary" @click="handleManage(record)">管理</a-button>
        </template>
        <template slot="application" v-if="isNewInvite"  slot-scope="text, record">
          <a-button  @click="handleManageNew(record)">应用管理</a-button>
        </template>
        <template slot="operations" slot-scope="text, record">
          <a-button type="danger" @click="handleRemove(record)">移除</a-button>
        </template>
      </a-table>
      <div class="record">
        <span
          class="cursor-pointer mr30"
          @click="handleRecordList('organizerRemoveRecordList')"
        >
          <a-icon type="file-done" class="mr10" />移除记录
        </span>
        <span
          v-if="!roleId"
          class="cursor-pointer"
          @click="handleRecordList('inviteRecordList')"
        >
          <a-icon type="solution" class="mr10" />邀请记录
        </span>
      </div>
    </a-card>
    <a-modal
      title="邀请人员"
      :visible="modalVisible"
      :confirm-loading="confirmLoading"
      :getContainer="getContainer"
      @ok="invitationHandleOk"
      @cancel="invitationHandleCancel"
    >
      <a-form-model
        :model="addUserForm"
        ref="addUserForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
      > 
        <a-form-model-item label="邀请方式" prop="invitationType">
            <a-select v-model="addUserForm.invitationType" placeholder="请选择邀请方式" @change="invitationChange">
              <a-select-option :value="item.value" v-for="(item, idx) in invitationWays" :key="idx">
                {{ item.label }}
              </a-select-option>
            </a-select>
        </a-form-model-item>
        <a-form-model-item label="姓名" prop="username" v-if="commonShow">
          <a-input
            v-model.trim="addUserForm.username"
            :maxLength="10"
            placeholder="请输入姓名"
          />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="phone" v-if="phoneShow">
          <a-input
            v-model.trim="addUserForm.phone"
            :maxLength="11"
            placeholder="请输入手机号"
          />
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email" v-if="emailShow">
          <a-input
            v-model.trim="addUserForm.email"
            :maxLength="50"
            placeholder="请输入邮箱"
          />
        </a-form-model-item>
        <a-form-model-item label="用户名" prop="account" v-if="usernameShow">
          <a-input
            v-model.trim="addUserForm.account"
            :maxLength="24"
            placeholder="用户名"
          />
        </a-form-model-item>
        <a-form-model-item label="组织身份" prop="roleId" class="form-item" v-if="commonShow">
          <a-select
            v-model.trim="addUserForm.roleId"
            placeholder="请选择组织身份"
            allowClear
            @focus="handleRoleFocus"
          >
            <a-select-option
              v-for="item in allRoleList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item v-if="isNewInvite" label="应用授权" prop="inviteAppsModel" class="form-item">
          <div v-for="(item, index) in inviteApps" :key="index">
            <span>{{item.systemName}}</span>
            <span>
              <a-select
                v-model="addUserForm.inviteAppsModel[index]"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择子系统"
                :options="item.options"
                @change="handleChange(index)"
              ></a-select>
            </span>
          </div>
        </a-form-model-item>
        <a-form-model-item label="单次邀请" prop="IsInviteOne">
          <a-radio-group disabled v-model="addUserForm.IsInviteOne">
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <selected-draw
      v-if="drawVisible"
      :visible="drawVisible"
      :selectOpenId="selectOpenId"
      :tableData="tableData"
      @closeDraw="closeDraw"
      @updateTable="updateTable"
    ></selected-draw>
  </div>
</template>

<script>
import { personnelColumns, tabMap } from "../data";
import { getUserList, addUser, delUser } from "@/services/userManage.js";
import { getAccountDetailNew } from "@/services/accountManage.js";
import { getAllRoleList } from "@/services/roleManage";
import { getClientsList, addUserNew, queryUserClient } from "@/services/newInvite"
import selectedDraw from './components/selectedDraw.vue'
import { mapGetters } from "vuex";
import Regex from "@/utils/regex.js";
import { commonValidate } from "@/utils/util"
import { INVITATION_TYPE_MAP } from "@/config/const"
import cloneDeep from 'lodash.clonedeep'
import { NAME_TIPS, NAME_EMPTY_TIPS, ACCOUNT_TIPS, ACCOUNT_EMPTY_TIPS } from "@/utils/consts";
import config from './config'
import store from '@/store'

// 邀请表单初始化json
const addUserFormJson = {
  invitationType: undefined, // 邀请方式
  phone: "",
  email: "",
  username: "", // 姓名
  account: "", // 用户名
  IsInviteOne: 1,
  roleId: undefined,
  inviteApps: [],
  inviteAppsModel: []
}

const fromSystem = store.getters['account/fromSystem']
const invitationWays = config[fromSystem] || config['default']

export default {
  name: "personnelManage",
  components: {
    'selected-draw': selectedDraw
  },
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      modalVisible: false,
      confirmLoading: false,
      personnelColumns,
      isLoading: false,
      isNewInvite: window.fromSystem === 'fleet-if' || window.fromSystem === 'tass' || window.fromSystem === 'user-center' || window.fromSystem === 'fleet-center' || window.fromSystem === 'isc-if',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      inviteAppsCopy: [],
      // ios：1，android：2，小程序：3，web：4，pc：5，iot：99）
      newInviteConfig: {
        1: 'ios',
        2: 'android',
        3: '小程序',
        4: 'web',
        // 5: 'pc',
        99: 'iot'
      },
      tableData: [],
      drawVisible: false,
      inviteApps: [],
      userData: [],
      addUserForm: cloneDeep(addUserFormJson),
      allRoleList: [],
      invitationWays,
      rules: {
        invitationType: [
          { required: true, message: "请选择邀请方式", trigger: "change" }
        ],
        username: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { validator: this.onCheckName, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: this.onCheckPhone, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: this.onCheckEmail, trigger: "blur" }
        ],
        account: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: this.onCheckAccount, trigger: "blur" }
        ],
        roleId: [
          { required: true, message: "请选择组织身份", trigger: "change" }
        ],
        IsInviteOne: [
          { required: true, message: "请选择是否只邀请一次用户", trigger: "change" }
        ],
        inviteAppsModel: [
          { required: true, validator: this.inviteAppsValidate, trigger: "change" }
        ]
      },
      selectOpenId: '',
      phoneShow: false, // 手机号显示
      emailShow: false, // 邮箱显示
      usernameShow: false, // 用户名显示
      commonShow: false // 姓名显示、组织身份显示
    };
  },
  watch: {
    "addUserForm.invitationType"(val) {
      const { phone, phoneEmail, phoneUserName, phoneUserNameEmail } = INVITATION_TYPE_MAP
      switch(val) {
        case phone:
          this.phoneShow = true;
          this.emailShow = false;
          this.usernameShow = false;
          this.commonShow = true;
          break;
        case phoneEmail:
          this.phoneShow = true;
          this.emailShow = true;
          this.usernameShow = false;
          this.commonShow = true;
          break;
        case phoneUserName:
          this.phoneShow = true;
          this.usernameShow = true;
          this.emailShow = false;
          this.commonShow = true;
          break;
        case phoneUserNameEmail:
          this.phoneShow = true;
          this.emailShow = true;
          this.usernameShow = true;
          this.commonShow = true;
          break;
        default:
          this.commonShow = false;
          this.phoneShow = false; // 手机号显示
          this.emailShow = false; // 邮箱显示
          this.usernameShow = false; // 用户名显示
      }
    }
  },
  mounted() {
    this.getAllRoleList();
    this.getUserList();
    if (this.isNewInvite) {
      this.getNewInviteList()
    }
  },
  computed: {
    ...mapGetters("account", ["enterpriseId"]),
    id() {
      return this.$route.query.id;
    },
    personnelColumnsPri() {
      if (!this.isNewInvite) {
        return this.personnelColumns.filter(item => item.dataIndex !== 'application')
      } else {
        return this.personnelColumns
      }
    },
    roleId() {
      return this.$route.query.roleId || "";
    },
    name() {
      return decodeURIComponent(this.$route.query.name);
    },
    roleName() {
      return decodeURIComponent(this.$route.query.roleName);
    },
    title() {
      let title = "组织人员";
      // roleId 代表 组织身份-- 人员列表入口进入
      if (this.roleId) {
        title = `${this.name} / ${this.roleName} / 组织人员`;
      } else {
        title = `${this.name} / 组织人员`;
      }
      return title;
    }
  },
  methods: {
    async handleManageNew(row) {
      this.drawVisible = true
      const res = await queryUserClient({
        appId: row.appId,
        openId: row.openId
      })
      this.selectOpenId = row.openId
      this.selectAppId = row.appId
      if (res.data.code === 200) {
        this.tableData = res.data.data
        this.tableData.forEach(item => {
          item.clientTypes = item.clientTypes.split(',')
        })
      }
    },
    async updateTable() {
      console.log(this.selectAppId, this.selectOpenId)
      const res = await queryUserClient({
        appId: this.selectAppId,
        openId: this.selectOpenId
      })
      if (res.data.code === 200) {
        this.tableData = res.data.data
        this.tableData.forEach(item => {
          item.clientTypes = item.clientTypes.split(',')
        })
      }
    },
    closeDraw() {
      this.drawVisible = false;
    },
    inviteAppsValidate(r, value) {
      let f = value.every(arr => arr.length === 0)
      console.log(value, f)
      if (f) {
        return Promise.reject('请至少选择一个子应用');
      } else {
        return Promise.resolve()
      }
    },
    handleChange(index) {
      if (!this.addUserForm.inviteAppsModel[index].length) {
        return
      }
      this.addUserForm.inviteApps[index].clientTypes = this.addUserForm.inviteAppsModel[index].join(',')
    },
    async getNewInviteList() {
      const appId = window.__POWERED_BY_QIANKUN__
          ? this.$store.state.account.appId
          : process.env.VUE_APP_ID; // 平台id
      const res = await getClientsList({
        appId
      })
      if(res.data.code === 200) {
        this.inviteApps = res.data.data
        this.inviteApps.forEach(item => {
          if (!Array.isArray(item.clientTypes)) {
            item.clientTypes = item.clientTypes.split(',').filter(i => i !== '5')
          }
          item.options = item.clientTypes.map(m => {
            return {
              label: this.newInviteConfig[m],
              value: m
            }
          })
        })
        this.inviteApps.forEach(item => {
          item.clientTypes = ''
        })
        this.addUserForm.inviteApps = JSON.parse(JSON.stringify(this.inviteApps))
        this.inviteAppsCopy = JSON.parse(JSON.stringify(this.inviteApps))
        this.addUserForm.inviteAppsModel = new Array(this.inviteApps.length).fill([])
      }
    },
    // 邀请change回调
    invitationChange(val) {
      this.addUserForm = cloneDeep(addUserFormJson); // 表单处理
      if (this.isNewInvite) {
        this.addUserForm.inviteApps = JSON.parse(JSON.stringify(this.inviteAppsCopy))
        this.addUserForm.inviteAppsModel = new Array(this.inviteApps.length).fill([])
      }
      this.addUserForm.invitationType = val; // 更新当前邀请类型
      this.$refs.addUserForm.clearValidate() // 清理所有校验
    },
    async getAllRoleList() {
      // 当有roleId时，不获取所有组织身份列表 --- 组织身份 / 人员列表
      if (this.roleId) return;
      let params = {
        departmentId: this.id,
        enterpriseId: this.enterpriseId
      };
      const {
        data: { data }
      } = await getAllRoleList(params);
      this.allRoleList = data.roleList || [];
    },
    // 基于手机号获取个人信息
    async getAccountDetailNew() {
      const params = {
        phone: this.addUserForm.phone
      }
      const resultApi = await getAccountDetailNew(params)
      const { code, data } = resultApi.data
      if (code !== 200) return
      const { account, email } = data
      Object.assign(this.addUserForm, { account, email })
    },
    // 手机号正则校验
    async onCheckPhone(rule, value, callback) {
      if (!value) {
        callback(new Error("手机号不能为空"));
        return
      }
      if (!Regex.phone.test(value)) {
        callback(new Error("请输入正确格式的手机号"));
        return;
      }
      callback();
      // 验证通过后，调用接口进行个人信息的赋值操作
      await this.getAccountDetailNew()
    },
    onCheckName(rule, value, callback) {
      if (!value) {
        callback(new Error(NAME_EMPTY_TIPS));
        return
      }
      let nameFlag = Regex.familyName.test(value) || Regex.familyNameEn.test(value) // 验证中英文
      nameFlag = nameFlag && Regex.familyNameDot.test(value) // 验证·的问题 不会有空格问题，因为输入trim
      if (!nameFlag) {
        callback(new Error(NAME_TIPS));
        return;
      }
      callback()
    },
    // 邮箱校验
    onCheckEmail(rule, value, callback) {
      if (!value) {
        callback(new Error("邮箱不能为空"));
        return
      }
      if (!Regex.email.test(value)) {
        callback(new Error("请输入正确格式的邮箱"));
        return;
      }
      callback();
    },
    // 用户名校验
    onCheckAccount(rule, value, callback) {
      if (!value) {
        callback(new Error(ACCOUNT_EMPTY_TIPS));
        return
      }
      if (!Regex.account.test(value)) {
        callback(new Error(ACCOUNT_TIPS));
        return;
      }
      callback()
    },
    async getUserList() {
      this.isLoading = true;
      let params = {
        departmentId: this.id,
        enterpriseId: this.enterpriseId,
        roleId: this.roleId,
        ...this.pagination
      };
      Object.prototype.hasOwnProperty.call(params, 'total') && delete params.total;
      try {
        const {
          data: {
            data: { users, total },
            code
          }
        } = await getUserList(params);
        this.isLoading = false;
        if (code === 200) {
          this.userData = users || [];
          this.pagination.total = total;
        }
      } catch (error) {
        this.isLoading = false;
      }
    },
    onTableChange({ current, pageSize }) {
      this.pagination.currentPage = current;
      this.pagination.pageSize = pageSize;
      this.getUserList();
    },
    handleManage(val) {
      this.$router.push({
        query: {
          id: this.id,
          key: tabMap.personnelManage,
          enterpriseId: val.enterpriseId,
          departmentId: val.departmentId
        }
      });
    },
    handleRemove(record) {
      let that = this;
      this.$confirm({
        title: "移除操作",
        content: () => (
          <div>
            你确定要移除该
            <span style="color:red;"> {record.name} </span>
            账号吗？
          </div>
        ),
        async onOk() {
          let params = {
            id: record.id,
            enterpriseId: that.enterpriseId,
            roleId: that.roleId,
            departmentId: that.id
          };
          const {
            data: { message, code }
          } = await delUser(params);
          if (code === 200) {
            that.$message.success("移除成功");
            let totalPage = Math.ceil((that.pagination.total - 1)/that.pagination.pageSize);
            let currentPage = that.pagination.currentPage > totalPage ? totalPage : that.pagination.currentPage;
            that.pagination.currentPage = that.pagination.currentPage < 1 ? 1 : currentPage;
            that.visible = false;
            that.getUserList();
          } else {
            that.$message.error(message);
          }
        }
      });
    },
    onAddUser() {
      this.modalVisible = true;
    },
    // 邀请点击确定
    async invitationHandleOk() {
      const validateResult = await commonValidate(this.$refs.addUserForm)
      if (!validateResult) return
      // 基于选择来移除非必要字段
      const params = cloneDeep(this.addUserForm)
      params.departmentId = this.id
      const { invitationType } = this.addUserForm
      const { phone, phoneEmail, phoneUserName } = INVITATION_TYPE_MAP
      switch(invitationType) {
        case phone:
          delete params.email
          delete params.account
          break;
        case phoneUserName:
          delete params.email
          break;
        case phoneEmail:
          delete params.account
          break;
        default:
      }
      if (this.isNewInvite) {
        delete params.inviteAppsModel;
        [...params.inviteApps].forEach((item, index) => {
          if (index === 0) {
            item.departmentId = params.departmentId
            item.roleId = params.roleId
            item.enterpriseId = this.enterpriseId
          }
          if(!item.clientTypes) {
            params.inviteApps.splice(index, 1)
          }
        })
        const { data: { code, message } } = await addUserNew(params)
        this.modalVisible = false;
        this.addUserForm.invitationType = undefined;
        if (code !== 200) {
          this.warning(message);
          return;
        }
        this.$refs.addUserForm.resetFields();
        this.$message.success("邀请成功");
        this.getUserList();
        return
      }
      const { data: { code, message } } = await addUser(params);
      this.modalVisible = false;
      this.addUserForm.invitationType = undefined;
      if (code !== 200) {
        this.warning(message);
        return;
      }
      this.$refs.addUserForm.resetFields();
      this.$message.success("邀请成功");
      this.getUserList();
    },
    // 点击邀请 取消
    invitationHandleCancel() {
      this.modalVisible = false;
      this.$refs.addUserForm.resetFields();
      this.$refs.addUserForm.clearValidate();
      this.phoneShow = false;
      this.emailShow = false;
      this.usernameShow = false;
      this.addUserForm.invitationType = undefined;
    },
    handleRecordList(val) {
      let key = tabMap[val];
      let { roleId, id, roleName, name } = this.$route.query;
      let path = '/car-team/system-qiankun/departmentManage-inviteRecordList-qiankun'
      if (val !== 'inviteRecordList') {
        // 邀请记录
        path = '/car-team/system-qiankun/departmentManage-organizerRemoveRecordList-qiankun'
      }
      if (this.$route.query.from && this.$route.query.from === 'inner') {
        path = '/car-team/system-qiankun/departmentManage-organizerRemoveRecordList-inner-qiankun'
      }
      this.$router.push({
        path,
        query: {
          id,
          key,
          name: name + ` / 组织人员`,
          roleName,
          roleId
        }
      });
    },
    warning(message) {
      const that = this;
      this.$warning({
        title: "信息提示",
        content: (
          <div style="color:red">
            该手机号({that.addUserForm.phone})--{message}
          </div>
        ),
        onOk() {
          that.modalVisible = false;
          that.addUserForm = {
            phone: "",
            roleId: undefined,
            IsInviteOne: 1
          };
        }
      });
    },
    handleRoleFocus() {
      if (!this.allRoleList.length) {
        this.$message.warning("暂无组织身份，请先新增组织身份！");
      }
    },
    goBack() {
      if (this.roleId) {
        // let key = tabMap.roleMange;
        // const { name, roleName, id } = this.$route.query;
        // this.$router.push({
        //   query: {
        //     id,
        //     key,
        //     name,
        //     roleName
        //   }
        // });
        this.$router.go(-1)
      } else {
        this.$router.go(-1)
      }
    },
    getContainer() {
      return document.querySelector('#invite-personel-warp')
    }
  }
};
</script>

<style lang="less" scoped>
.personnel-manage-list {
  ::v-deep .ant-card-head-title {
    font-weight: 600;
    padding: 12px 0;
    font-size: 18px;
  }

  .record {
    position: absolute;
    left: 24px;
    bottom: 28px;
    color: #3d6cf7;
    z-index: 100;
  }
}
</style>
